/********************************************************************************
 * Project Name		[JavaEE_Web]
 * File Name     	[ListFileServlet.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package file.download;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import file.upload.commons.FileUploadConstants;

/**
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
@WebServlet(value = "/listFileServlet")
public class ListFilesServlet extends HttpServlet {

	private static final long serialVersionUID = -5908435947783319286L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Properties properties = (Properties) request.getServletContext().getAttribute("fileConfig");
		String filePath = properties.getProperty(FileUploadConstants.FILE_PATH);

		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html,charset=UTF-8");

		Map<String, String> files = this.listAllFils(new File(filePath));
		request.setAttribute("map", files);
		request.getRequestDispatcher("/jsp/filedownload/listFile.jsp").forward(request, response);
	}

	private Map<String, String> listAllFils(File directory) {
		Map<String, String> map = new HashMap<>();

		if (!directory.isFile()) {
			File[] files = directory.listFiles();
			for (File file : files) {
				if (file.isDirectory()) {
					listAllFils(file);
				} else {
					String realFileName = file.getName().substring(file.getName().indexOf('_') + 1);
					map.put(file.getName(), realFileName);
				}
			}
		} else {
			String realFileName = directory.getName().substring(directory.getName().indexOf('_') + 1);
			map.put(directory.getName(), realFileName);
		}

		return map;
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}
}
